package com.foryang.springcloud.controller;

import com.foryang.springcloud.util.FastDFSUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

@RestController
public class FastDFSController {

    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        String[] result = FastDFSUtil.upload(file.getInputStream(),file.getOriginalFilename());
        if(result != null){
            System.out.println(Arrays.toString(result));
            return "SUCCESS";
        }
        return "FAIL";
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response){
        String filename = "M00/00/00/wKgBBmAs_kyAFxNPAAETXcmxiKE990.jpg";
        byte[] file = FastDFSUtil.download("group1",filename);

        response.setContentType("application/x-download");
        response.setHeader("content-disposition", "attachement;filename=00wKgBBmAsyDOACLZGAAETXcmxiKE161.jpg");
        InputStream inputStream = null;
        try {
            int len = 0;
            inputStream = new ByteArrayInputStream(file);
            byte buffer[] = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = inputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }

}
